<?php


namespace App\Http\Controllers\Merchant;
use App\Http\Controllers\BaseController;
use App\Jobs\DeleteStar;
use App\Jobs\VideoShortUrl;
use App\Lib\QiNiuAdapter;
use App\Models\Category;
use App\Models\Cookbook;
use App\Models\Merchant;
use App\Models\Star;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class CookbookController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');
        $category_id = $request->input('category_id');
        $parent_category_id = $request->input('parent_category_id');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $audit_status = $request->input('audit_status', -1);
        $is_vip = $request->input('is_vip', -1);
        $is_free = $request->input('is_free', -1);
        $is_on = $request->input('is_on', -1);
        $merchant_id = $this->getUserId();

        $users = Cookbook::where('merchant_id', $merchant_id)->when($title, function ($q)use($title) {
            $q->where('title', 'like', '%' . $title . '%');
        })->when($category_id, function ($q)use($category_id) {
            $arr_category_id = explode(",", $category_id);
            $q->whereIn('category_id', $arr_category_id);
        })->when($start_at, function ($q)use($start_at) {
            $q->where('created_at', '>=', $start_at);
        })->when($end_at, function ($q)use($end_at) {
            $end_at = date('Y-m-d', strtotime($end_at) + 24 * 3600);
            $q->where('created_at', '<', $end_at);
        })->when($is_on != -1, function ($q)use($is_on) {
            $q->where('is_on', '=', $is_on);
        })->when($audit_status != -1, function ($q)use($audit_status) {
            $q->where('audit_status', '=', $audit_status);
        })->when($is_free != -1, function ($q)use($is_free) {
            $q->where('is_free', '=', $is_free);
        })->when($is_vip != -1, function ($q)use($is_vip) {
            $q->where('is_vip', '=', $is_vip);
        })->parentCategory($parent_category_id)->withCertain('parent_category', ['title'])->with('category')
            ->orderBy('sort', 'desc')->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));


        return $this->paginate($users);
    }

    /**
     * 详情
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function info(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:cookbooks'
        ]);
        $id = \request("id");
        $info = Cookbook::with('category')->with(['product' => function($q) {
            $q->select('title', 'mall_products.id', 'image_url');
        }])->find($id);
        return $this->success($info);
    }

    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $input = $request->input();
        $merchant = $this->getUser();
        $input['merchant_id'] = $this->getUserId();
        $id = \request("id");
        $input['price'] = 0;
        if ($input['is_free'] != 0) {
            $input['price'] = $input['price_yuan'] * 100;
        }
        $category = Category::find($input['category_id']);
        if (!$category)
            return $this->failed('分类id不存在');
        $input['parent_category_id'] = $category->parent_id;
        $product_ids = $input['product_ids'] ?? '';
        $arr_product_id = $product_ids ? explode(",", $product_ids) : [];

        if ($id) {
            $cookbook = Cookbook::find($id);
            if (!$cookbook) {
                return $this->failed("id对应数据不存在");
            }
            $old_cookbook = clone $cookbook;
            $cookbook->thumb_media_id = null;
            $cookbook->update($input);
            if ($old_cookbook->video_url != $input['video_url']) {
//                dispatch(new VideoShortUrl($id));
                QiNiuAdapter::deleteResource($old_cookbook->video_url);
                QiNiuAdapter::deleteResource($old_cookbook->short_video_url);
            }
        } else {
            $cookbook = Cookbook::create($input);
            $merchant->increment('cookbook_num', 1);
            $id = $cookbook->id;
//            dispatch(new VideoShortUrl($id));
        }

        $cookbook->product()->sync($arr_product_id);

        return $this->success($id);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $model = Cookbook::find($id);
            $short_video_url = $model->short_video_url;
            $video_url = $model->video_url;
            if ($model->delete()) {
                if ($short_video_url) {
                    QiNiuAdapter::deleteResource($short_video_url);
                }
                if ($video_url) {
                    QiNiuAdapter::deleteResource($video_url);
                }
                $merchant = Merchant::find ($model->merchant_id);
                if ($merchant->cookbook_num)
                    $merchant->increment('cookbook_num', -1);

                dispatch(new DeleteStar(Star::TYPE_COOKBOOK, $id));
            }
        }
        return $this->success([]);
    }

    public function isOn(Request $request) {
        $this->validate($request, [
            'ids' => 'required',
            'status' => 'required'
        ]);
        $status = \request('status');
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        $list = Cookbook::whereIn('id', $arr_id)->get();
        foreach ($list as $item) {
//            if ($item->audit_status != 1) {
//                continue;
//            }
            if ($item->is_on == $status) {
                continue;
            }
            $item->is_on = $status;
            $item->save();
        }
        return $this->success([]);
    }


}

